How to create and initialize a Slice in Go Programming? | Go Programming Language
In this article, you will learn about how to create and initialize a Slice in Go Programming Language.
In GoLang, a slice can be created and initialized using the following ways:
- Using slice Literal: The user can create a slice using the slice literal. The creation of a slice literal is just like an array literal, but the one difference is that you are not allowed to specify the size of the slice in the square braces[ ].
Syntax:
var slice_name = [ ] string{ “Tutorial”, “Links” }
Note: Always remember when you create a slice using a string literal, then it first has to create an array and after that, it returns a slice reference.
- Using an Array: We already know, the slice is the reference of the array so the user can create a slice from the given array. For creating a slice in the GoLang from the given array first you have to mention the lower and upper bound, which means the slice can take the items from the array starting from the lower bound to the upper bound. It does not include the items above from the upper bound.
Syntax:
Array_name[low:high]
This will return a new slice.
Note: The default value of the lower bound is 0 and the default value of the upper bound is the total number of items present in the given array.
- Using already Existing Slice: It is also allowed to create a slice from the specific slice. For creating a slice from the given slice first you have to mention the lower and upper bound, which means the slice can take the items from the given slice starting from the lower bound to the upper bound. It does not include the items above from the upper bound.
Syntax:
name_ofslice[low:high]
It will return a new slice.
Note: The default value of the lower bound is 0 and the default value of the upper bound is the total items present in the specific slice.
- Using the make() function: The user can create a slice using the make() function which is provided by the available Go library. This function takes the three parameters, i.e, type, length, and capacity. Here, the value of the capacity is optional. It assigns an underlying array with a size that is equal to the given capacity and returns a slice that refers to the underlying array. However, the make() function is used to create an empty slice. The empty slices are those slices that contain an empty array reference.
Syntax:
func make([ ]T, len, cap) [ ]T


